<script setup>
import { onMounted, ref } from 'vue'
import { useStore } from 'vuex'
import axios from 'axios'
import router from '../../router/router'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
const route = useRoute()
const store = useStore()
const startTime = ref(null)
const endTime = ref(null)
const time = ref(null)
const reduceAnswer = ref([])
// eslint-disable-next-line no-unused-vars
const answerScore = ref(0)
// eslint-disable-next-line camelcase
const bg_flag = ref(false)// 左侧显示隐藏标识符
const isFillClick = ref(false)
// eslint-disable-next-line camelcase
const slider_flag = ref(true)
const currentType = ref(1)// 当前题型类型  1--选择题  2--填空题  3--判断题
const radio = ref([])// 保存考生所有选择题的选项
const title = ref('请选择正确选项')
const userInfoName = ref(store.state.userStore.userInfo.data.data.studentName)
const userInfoId = ref(store.state.userStore.userInfo.data.data.studentId)
const topicCount = ref([])// 每种类型题目的总数
const score = ref([])
const examData = ref({

})
const topic = ref({}

)// 试卷信息
const showQuestion = ref({}) // 当前显示题目信息
const showAnswer = ref({})// 当前题目对应的答案选项
const number = ref(1)
const part = ref(0)
const fillAnswer = ref([[]])
const judgeAnswer = ref([])
// eslint-disable-next-line no-unused-vars
const rightAnswer = ref('')
const examCode = route.query.examCode

const allindex = ref(0)// 全局index

onMounted(() => {
  getExamData()

  showTime()
})

const getExamData = () => { // 获取当前试卷所有信息
  const date = new Date()
  startTime.value = getTime(date)
  // 获取路由传递过来的试卷编号
  axios.get('api/examManagecontroller/findById/' + examCode).then(res => { // 通过examCode请求试卷详细信息
    examData.value = res.data// 获取考试详情
    time.value = examData.value.totalScore// 获取分钟数
    const paperId = examData.value.paperId

    axios.get('api/papercontroller/paper/' + paperId).then(res => { // 通过paperId获取试题题目信息
      topic.value = res.data
      // const reduceAnswer = res.data[1][index.value]
      const keys = Object.keys(topic.value)// 对象转数组
      keys.forEach(e => {
        const data = res.data[e]
        topicCount.value.push(data.length)
        // eslint-disable-next-line prefer-const
        let currentScore = 0
        for (let i = 0; i < data.length; i++) { // 循环每种题型,计算出总分
          currentScore += data[i].score
        }
        score.value.push(currentScore)// 把每种题型总分存入score
      })
      const len = topicCount.value[1]// 填空题长度
      const father = []
      for (let i = 0; i < len; i++) { // 根据填空题数量创建二维空数组存放每道题答案
        const children = [null, null, null, null]
        father.push(children)
      }
      fillAnswer.value = father
      console.log(topic.value)
      const dataInit = topic.value[1]
      number.value = 1
      showQuestion.value = dataInit[0].question
      showAnswer.value = dataInit[0]
    })
  })
}

const getTime = (date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  const day = date.getDate < 10 ? '0' + date.getDate() : date.getDate()

  return year + '-' + month + '-' + day
}

const change = (index1) => { // 选择题
  allindex.value = index1
  // eslint-disable-next-line no-unused-vars
  const reduceAnswer = topic.value[1][allindex]
  isFillClick.value = true
  currentType.value = 1
  const len = topic.value[1].length
  if (allindex.value < len) {
    if (allindex.value <= 0) {
      allindex.value = 0
    }
    console.log(`总长度${len}`)
    console.log(`当前index:${allindex.value}`)
    title.value = '请选择正确的选项'
    const Data = topic.value[1]
    // console.log(Data)
    showQuestion.value = Data[allindex.value].question // 获取题目信息
    showAnswer.value = Data[allindex.value]
    number.value = allindex.value + 1
  } else if (allindex.value >= len) {
    allindex.value = 0
    fill(allindex.value)
  }
}
const fillBG = () => { // 填空题已答题目 如果已答该题目,设置第四个元素为true为标识符
  console.log(fillAnswer.value[allindex.value])
  if (fillAnswer.value[allindex.value][0] != null) {
    fillAnswer.value[allindex.value][3] = true
  }
}
const fill = (index2) => { // 填空题
  allindex.value = index2
  const len = topic.value[2].length
  currentType.value = 2
  if (allindex.value < len) {
    if (allindex.value < 0) {
      allindex.value = topic.value[1].length - 1
      change(allindex.value)
    } else {
      console.log(`总长度${len}`)
      console.log(`当前index:${allindex.value}`)
      title.value = '请在横线处填写答案'
      const Data = topic.value[2]
      showQuestion.value = Data[allindex.value].question // 获取题目信息
      console.log(showQuestion.value)
      part.value = showQuestion.value.split('()').length - 1 // 根据题目中括号的数量确定填空横线数量
      number.value = topicCount.value[0] + allindex.value + 1
    }
  } else if (allindex.value >= len) {
    allindex.value = 0
    judge(allindex.value)
  }
}
const judge = (index3) => { // 判断题
  allindex.value = index3
  const len = topic.value[3].length
  currentType.value = 3
  if (allindex.value < len) {
    if (allindex.value < 0) {
      allindex.value = topic.value[2].length - 1
      fill(allindex.value)
    } else {
      console.log(`总长度${len}`)
      console.log(`当前index:${allindex.value}`)
      title.value = '请作出正确判断'
      const Data = topic.value[3]
      showQuestion.value = Data[allindex.value].question // 获取题目信息
      number.value = topicCount.value[0] + topicCount.value[1] + allindex.value + 1
    }
  } else if (allindex.value >= len) {
    allindex.value = 0
    change(allindex.value)
  }
}
const getChangeLabel = (val) => { // 获取选择题作答选项
  /* 保存学生答题选项 */
  radio[allindex] = val
  console.log(radio.value)
  if (val) {
    const data = topic.value[1]
    bg_flag.value = true
    // eslint-disable-next-line dot-notation
    data[allindex.value]['isClick'] = true
  }
}
const getJudgeLabel = (val) => { // 获取判断题作答选项
  judgeAnswer[allindex] = val
  if (val) {
    const data = topic.value[3]
    bg_flag.value = true
    // eslint-disable-next-line dot-notation
    data[allindex.value]['isClick'] = true
  }
}
const previous = () => { // 上一题
  allindex.value--
  console.log(allindex.value)
  switch (currentType.value) {
    case 1:
      change(allindex.value)
      break
    case 2:
      fill(allindex.value)
      break
    case 3:
      judge(allindex.value)
      break
  }
}

const next = () => { // 下一题
  allindex.value++
  console.log(allindex.value)
  switch (currentType.value) {
    case 1:
      change(allindex.value)
      break
    case 2:
      fill(allindex.value)
      break
    case 3:
      judge(allindex.value)
      break
  }
}
const mark = () => { // 标记功能
  switch (currentType.value) {
    case 1:
      // eslint-disable-next-line dot-notation
      topic.value[1][allindex.value]['isMark'] = true // 选择题标记
      break
    case 2:
      // eslint-disable-next-line dot-notation
      topic.value[2][allindex.value]['isMark'] = true // 填空题标记
      break
    case 3:
      // eslint-disable-next-line dot-notation
      topic.value[3][allindex.value]['isMark'] = true // 判断题标记
  }
}
const commit = () => { // 答案提交计算分数
  /* 计算选择题总分 */
  const finalScore = ref(0)
  console.log(radio.value)
  radio.value.forEach((element, index) => { // 循环每道选择题根据选项计算分数
    console.log(element)
    const right = ref(null)
    if (element != null) {
      switch (element) { // 选项1,2,3,4 转换为 "A","B","C","D"
        case 1:
          right.value = 'A'
          break
        case 2:
          right.value = 'B'
          break
        case 3:
          right.value = 'C'
          break
        case 4:
          right.value = 'D'
      }
      if (right.value === topic.value[1][index].rightAnswer) { // 当前选项与正确答案对比
        finalScore.value += topic.value[1][index].score // 计算总分数
      }
      // console.log(right, topic.value[1][index].rightAnswer)
    }
    // console.log(topic1Answer)
  })
  /** 计算填空题总分 */
  // console.log(`this.fillAnswer${this.fillAnswer}`)
  // console.log(this.topic[2][this.index])
  fillAnswer.value.forEach((element, index) => { // 此处index和 this.index数据不一致，注意
    element.forEach((inner) => {
      if (topic.value[2][index].answer.includes(inner)) { // 判断填空答案是否与数据库一致
        console.log('正确')
        finalScore.value += topic.value[2][index].score
      }
    })
  })
  /** 计算判断题总分 */

  judgeAnswer.value.forEach((element, index) => {
    const right = ref(null)
    switch (element) {
      case 1:
        right.value = 'T'
        break
      case 2:
        right.value = 'F'
    }
    if (right.value === topic.value[3][index].answer) { // 当前选项与正确答案对比
      finalScore.value += topic.value[3][index].score // 计算总分数
    }
  })
  console.log(`目前总分${finalScore.value}`)
  if (time.value !== 0) {
    console.log('交卷')
    const date = new Date()
    console.log('时间')
    console.log(date)
    endTime.value = getTime(date)
    const answerDate = endTime.value.substr(0, 10)
    // 提交成绩信息
    axios.post('api/scorecontroller/addscore', {
      examCode: examData.value.examCode, // 考试编号
      studentId: userInfoId.value, // 学号
      subject: examData.value.source, // 课程名称
      etScore: finalScore.value, // 答题成绩
      answerDate: answerDate // 答题日期

    }).then(res => {
      if (res.data === 1) {
        console.log(answerDate)
        router.push({
          path: '/studentScore',
          query: {
            score: finalScore.value,
            startTime: startTime.value,
            endTime: endTime.value
          }
        })
      }
    })
      .catch(() => {
        console.log('继续答题')
      })
  }
}

const showTime = () => { // 倒计时
  setInterval(() => {
    time.value -= 1
    if (time.value === 10) {
      ElMessage.error('考生注意,考试时间还剩10分钟！！！')

      if (time.value === 0) {
        console.log('考试时间已到,强制交卷。')
      }
    }
  }, 1000 * 60)
}

</script>

<template>

<div id="answer">
  <!-- 顶部信息栏 -->
  <div class="top">
    <ul class="item">
      <li><i class="iconfont icon-menufold icon20" ref="toggle" @click="slider_flag= !slider_flag"></i></li>
    <li>{{examData.type}}-{{examData.source}}</li>
    <el-dropdown>
    <span class="el-dropdown-link">

      <el-icon><User /></el-icon>
    </span>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item> <p>姓名：{{userInfoName}}</p></el-dropdown-item>
        <el-dropdown-item><p>准考证号：{{userInfoId}}</p></el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
    </ul>
  </div>
  <div class="flexarea">
    <!-- 左边题目编号区 -->
    <transition name="slider-fade">
      <div class="left" v-if="slider_flag">
        <ul class="l-top">
          <li><a href="javacript:;"></a><span>当前</span></li>
          <li><a href="javacript:;"></a><span>未答</span></li>
          <li><a href="javacript:;"></a><span>已答</span></li>
          <li><a href="javacript:;"></a><span>标记</span></li>
        </ul>
        <div class="l-bottom">
          <div class="item">
            <p>选择题部分</p>
            <ul>
              <li v-for="(list,index1) in topic[1]" :key="index1">
              <a href="javacript:;"
                  @click="change(index1)"
                 :class="{'border': allindex == index1 && currentType == 1,'bg': bg_flag && topic[1][index1].isClick == true}">
                  <span :class="{'mark' :topic[1][index1].isMark==true}"></span>
                  {{index1+1}}
                  </a>
              </li>
            </ul>
          </div>
          <div class="item">
            <p>填空题部分</p>
            <ul>
              <li v-for="(list,index2) in topic[2]" :key="index2">
                <a href="javacript:;"
                @click="fill(index2)"
                :class="{ 'border': allindex == index2 && currentType == 2, 'bg': fillAnswer[index2][3] == true}">
                <span :class="{'mark': topic[2][index2].isMark == true}">
                </span>{{topicCount[0]+index2+1}}</a>
              </li>
            </ul>
          </div>
          <div class="item">
            <p>判断题部分</p>
                <ul>
                  <li v-for="(list, index3) in topic[3]" :key="index3">
                    <a href="javacript:;"
                    @click="judge(index3)"
                   :class="{'border': allindex == index3 && currentType == 3,'bg': bg_flag && topic[3][index3].isClick == true}">
                    <span :class="{'mark': topic[3][index3].isMark == true}">
                    </span>{{topicCount[0]+topicCount[1]+index3+1}}</a>
                  </li>
                </ul>
          </div>
           <div class="final" @click="commit()">结束考试</div>
        </div>
      </div>
    </transition>

    <transition name="slider-fade">
      <div class="right">
        <div class="title">
          <p>{{title}}</p>
          <i class="iconfont icon-right auto-right"></i>
          <span>全卷共{{topicCount[0]+topicCount[1]+topicCount[2]}}题
          <i class="iconfont icon-time"></i>倒计时：<b>{{time}}</b>分钟</span>
        </div>

        <!-- 选择 -->
        <div class="content">
          <p class="topic"><span class="number">{{number}}</span>{{showQuestion}}</p>
          <div v-if="currentType==1">
          <el-radio-group v-model="radio[allindex]" @change="getChangeLabel">
          <el-radio :label="1">{{showAnswer.answerA}}</el-radio>
          <el-radio :label="2">{{showAnswer.answerB}}</el-radio>
          <el-radio :label="3">{{showAnswer.answerC}}</el-radio>
          <el-radio :label="4">{{showAnswer.answerD}}</el-radio>
          </el-radio-group>
          <div class="analysis" v-if="isPractice">
                <ul>
                  <li> <el-tag type="success">正确姿势：</el-tag><span class="right">{{reduceAnswer.rightAnswer}}</span></li>
                  <li><el-tag>题目解析：</el-tag></li>
                  <li>{{reduceAnswer.analysis == null ? '暂无解析': reduceAnswer.analysis}}</li>
                </ul>
              </div>
            </div>
            <!-- 填空 -->
            <div class="fill" v-if="currentType == 2">
              <div v-for="(item,currentIndex) in part" :key="currentIndex">
                <el-input placeholder="请填在此处"
                  v-model="fillAnswer[allindex][currentIndex]"
                  clearable
                  @blur="fillBG">
                </el-input>
              </div>
              <div class="analysis" v-if="isPractice">
                <ul>
                  <li> <el-tag type="success">正确姿势：</el-tag><span class="right">{{topic[2][allindex].answer}}</span></li>
                  <li><el-tag>题目解析：</el-tag></li>
                  <li>{{topic[2][allindex].analysis == null ? '暂无解析': topic[2][allindex].analysis}}</li>
                </ul>
              </div>
            </div>

            <!-- 判断 -->
            <div class="judge" v-if="currentType == 3">
              <el-radio-group v-model="judgeAnswer[allindex]" @change="getJudgeLabel" v-if="currentType == 3">
                <el-radio :label="1">正确</el-radio>
                <el-radio :label="2">错误</el-radio>
              </el-radio-group>
              <div class="analysis" v-if="isPractice">
                <ul>
                  <li> <el-tag type="success">正确姿势：</el-tag><span class="right">{{topic[3][allindex].answer}}</span></li>
                  <li><el-tag>题目解析：</el-tag></li>
                  <li>{{topic[3][allindex].analysis == null ? '暂无解析': topic[3][allindex].analysis}}</li>
                </ul>
              </div>
          </div>
        </div>
          <div class="operation">
            <ul class="end">
              <li @click="previous()"><i class="iconfont icon-previous"></i><span>上一题</span></li>
              <li @click="mark()"><i class="iconfont icon-mark-o"></i><span>标记</span></li>
              <li @click="next()"><span>下一题</span><i class="iconfont icon-next"></i></li>
            </ul>
          </div>
      </div>
    </transition>
  </div>
</div>
</template>

<style  lang="less" scoped>
 .el-input__inner{
border-radius:0; // 去除圆角
    border-top: 0px;
    border-left-width: 0px;
    border-right-width: 0px;
    border-bottom-width: 1px;

}
.iconfont.icon-time {
  color: #2776df;
  margin: 0px 6px 0px 20px;
}
.analysis {
  margin-top: 20px;
  .right {
    color: #2776df;
    font-size: 18px;
    border: 1px solid #2776df;
    padding: 0px 6px;
    border-radius: 4px;
    margin-left: 20px;
  }
  ul li:nth-child(2) {
    margin: 20px 0px;
  }
  ul li:nth-child(3) {
    padding: 10px;
    background-color: #d3c6c9;
    border-radius: 4px;
  }
}
.analysis span:nth-child(1) {
  font-size: 18px;
}
.mark {
  position: absolute;
  width: 4px;
  height: 4px;
  content: "";
  background-color: red;
  border-radius: 50%;
  top: 0px;
  left: 22px;
}
.border {
  position: relative;
  border: 1px solid #FF90AA !important;

}
.bg {
  background-color: #5188b8 !important;

}
.fill .el-input {
  display: inline-flex;
  width: 150px;
  margin-left: 20px;

    padding-left: 20px;

}
/* slider过渡效果 */
.slider-fade-enter-active {
  transition: all .3s ease;
}
.slider-fade-leave-active {
  transition: all .3s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slider-fade-enter, .slider-fade-leave-to {
  transform: translateX(-100px);
  opacity: 0;
}

.operation .end li:nth-child(2) {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: rgb(39, 118, 223);
  border-radius: 50%;
  width: 50px;
  height: 50px;
  color: #fff;
}
.operation .end li {
  cursor: pointer;
  margin: 0 100px;
}
.operation {
  background-color: #fff;
  border-radius: 4px;
  padding: 10px 0px;
  margin-right: 10px;
}
.operation .end {
  display: flex;
  justify-content: center;
  align-items: center;
  color: rgb(39, 118, 223);
}
.content .number {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 20px;
  height: 20px;
  background-color: rgb(39, 118, 223);
  border-radius: 4px;
  margin-right: 4px;
}
.content {
  padding: 0px 20px;
}
.content .topic {
  padding: 20px 0px;
  padding-top: 30px;
}
.right .content {
  background-color: #fff;
  margin: 10px;
  margin-left: 0px;
  height: 470px;
}
.content .el-radio-group label {
  color: #000;
  margin: 5px 0px;
}
.content .el-radio-group {
  display: flex;
  flex-direction:column;
}
.right .title p {
  margin-left: 20px;
}
.flexarea {
  display: flex;
}
.flexarea .right {
  flex: 1;
}
.auto-right {
  margin-left: auto;
  color: #2776df;
  margin-right: 10px;
}
.right .title {
  margin-right: 10px;
  padding-right: 30px;
  display: flex;
  margin-top: 10px;
  background-color: #fff;
  height: 50px;
  line-height: 50px;
}
.clearfix {
  clear: both;
}
.l-bottom .final {
  cursor: pointer;
  display: inline-block;
  text-align: center;
 background-color: rgb(39, 118, 223);
  width: 240px;
  margin: 20px 0px 20px 10px;
  border-radius: 4px;
  height: 30px;
  line-height: 30px;
  color: #fff;
  margin-top: 22px;
}
#answer .left .item {
  padding: 0px;
  font-size: 16px;
}
.l-bottom {
  border-radius: 4px;
  background-color: #fff;
}
.l-bottom .item p {
  margin-bottom: 15px;
  margin-top: 10px;
  color: #000;
  margin-left: 10px;
  letter-spacing: 2px;
}
.l-bottom .item li {
  width: 15%;
  margin-left: 5px;
  margin-bottom: 10px;
}
.l-bottom .item {
  display: flex;
  flex-direction: column;
}
.l-bottom .item ul {
  width: 100%;
  margin-bottom: -8px;
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}
.l-bottom .item ul li a {
  position: relative;
  justify-content: center;
  display: inline-flex;
  align-items: center;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background-color: #fff;
  border: 1px solid #eee;
  text-align: center;
  color: #000;
  font-size: 16px;
}
.left .l-top {
  display: flex;
  justify-content: space-around;
  padding: 16px 0px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 10px;
  background-color: #fff;
}
.left {
  width: 260px;
  height: 100%;
  margin: 10px 10px 0px 10px;
}
.left .l-top li:nth-child(2) a {
  border: 1px solid #eee;
}
.left .l-top li:nth-child(3) a {
  background-color: #5188b8;
  border: none;
}
.left .l-top li:nth-child(4) a {
  position: relative;
  border: 1px solid #eee;
}
.left .l-top li:nth-child(4) a::before {
  width: 4px;
  height: 4px;
  content: " ";
  position: absolute;
  background-color: red;
  border-radius: 50%;
  top: 0px;
  left: 16px;
}
.left .l-top li {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.left .l-top li a {
  display: inline-block;
  padding: 10px;
  border-radius: 50%;
  background-color: #fff;
  border: 1px solid #FF90AA;
}
#answer .top {
  background-color: rgb(39, 118, 223);
}
#answer .item {
  color: #fff;
  display: flex;
  padding: 20px;
  font-size: 20px;
}
#answer .top .item li:nth-child(1) {
  margin-right: 10px;
}
#answer .top .item li:nth-child(3) {
  position: relative;
  margin-left: auto;
}
#answer {
  padding-bottom: 30px;
}
.icon20 {
  font-size: 20px;
  font-weight: bold;
}
.item .msg {
  padding: 10px 15px;
  border-radius: 4px;
  top: 47px;
  right: -30px;
  color: #6c757d;
  position: absolute;
  border: 1px solid rgba(0,0,0,.15);
  background-color: #fff;
}
.item .msg p {
  font-size: 16px;
  width: 200px;
  text-align: left;
}
.judge{
  float: left;
}
</style>
